﻿using UnityEngine;
using UniRx;

/// <summary>
/// 漫步
/// </summary>
public class AIStateWander : AIStateBase
{
    protected override string GetName() => "wander";

    private Timer.Simple m_Timer = new Timer.Simple();
    private float m_Duration;
    private EdgeChecker m_EdgeChecker;

    private float m_Axis;

    protected override void OnInit()
    {
        m_EdgeChecker = ai.entity.physics.edgeChecker;
        m_Timer.onFinish.Subscribe(_ => StartTimer()).AddTo(ai.entity);
    }

    protected override void OnEnter()
    {
        StartTimer();
    }

    protected override void OnExecute()
    {
        if (m_EdgeChecker.isEdge)
        {
            m_Timer.ShutDown();
            StartTimer();
        }
        ai.outputs.SetAxis("horizontalAxis", m_Axis);
    }

    protected override void OnExit()
    {
        if (m_Timer.isRuning)
        {
            m_Timer.ShutDown();
        }
    }

    private void StartTimer()
    {
        m_Axis = GetAxis();
        m_Duration = GetDuration();
        m_Timer.Start(m_Duration);
    }

    private long GetAxis()
    {
        if (m_EdgeChecker.isEdge)
        {
            var dir = ai.entity.animator.direction.x;
            if (dir > 0) return -1;
            if (dir < 0) return 1;
        }
        return Random.Range(-1, 2);
    }

    private float GetDuration()
    {
        return Random.Range(UnitDefine.AI_STATE_RANDOM_MIN_DURATION, UnitDefine.AI_STATE_RANDOM_MAX_DURATION);
    }
}